// ============ 全局变量 ============
const url = "/api/rest/user";
// 获取新增按钮的DOM
let addForm = document.getElementById('add-form');
let gridInstance = null;
let userData = null;

// 列表表头及操作按钮配置
/*let columns = [
      { name: '#', id: 'id', width: '8%' },
      { name: '用户名', id: 'username', sort: true },
      { name: '姓名', id: 'name', sort: true },
      { name: '邮箱', id: 'email', sort: true },
      { name: '电话', id: 'phone', sort: true },
      { name: '创建时间', id: 'createAt', sort: true },
      { name: '状态', id: 'enableState', sort: true },
      { name: '部门', id: 'dept.name', sort: true },
      {
          name: '操作',
          id: 'actions',
          width: '20%',
          formatter: (_, row) => gridjs.html(`
              <button type="button" data-bs-toggle="modal" data-bs-target="#editModal" class="btn btn-sm btn-outline-primary m-1"><i class="fas fa-edit" ></i> 编辑</button>
              <button type="button" onclick="toggle('${row.cells[0].data}')" class="btn btn-sm btn-outline-${row.cells[6].data === '启用' ? 'danger' : 'success'} m-1"><i class="fas fa fa-exchange" ></i> ${row.cells[6].data === '启用' ? '停用' : '启用'}</button>
          `)
      }
    ]*/

const gridOptions = {
    columns: [
      { name: '#', id: 'id', width: '8%' },
      { name: '用户名', id: 'username', sort: true },
      { name: '姓名', id: 'name', sort: true },
      { name: '邮箱', id: 'email', sort: true },
      { name: '电话', id: 'phone', sort: true },
      { name: '创建时间', id: 'createAt', sort: true },
      { name: '状态', id: 'enableState', sort: true },
      { name: '部门', id: 'dept.name', sort: true },
      {
        name: '操作',
        id: 'actions',
        width: '20%',
        formatter: (_, row) => gridjs.html(`
          <button type="button" data-bs-toggle="modal" data-bs-target="#editModal" class="btn btn-sm btn-outline-primary m-1"><i class="fas fa-edit" ></i> 编辑</button>
          <button type="button" onclick="toggle('${row.cells[0].data}')" class="btn btn-sm btn-outline-${row.cells[6].data === '启用' ? 'warning' : 'success'} m-1"><i class="fas fa fa-exchange" ></i> ${row.cells[6].data === '启用' ? '停用' : '启用'}</button>
        `)
      }
    ],
    // data: userData,
    server: {
        url: url,
        then: data => {
            userData = data.content
            return data.content.map(
                user => [
                    user.id,
                    user.username,
                    user.name,
                    user.email,
                    user.phone,
                    user.createAt,
                    user.enableState,
                    user.dept.name
                ]
            )
        },
        total: data => data.totalElements
    },
    pagination: {
      limit: 5, // 每页5条
      server: {
        url: (prev, page, limit) => addQueryParam(prev, `size=${limit}&page=${page}`)
      }
    },
    search: false,
    sort: true,   // 启用排序
    language: {
      pagination: {
        previous: '上一页',
        next: '下一页',
        showing: '显示第',
        of: '条，共',
        to: '至',
        results: '条记录'
      }
    }
}

const searchForm = document.getElementById('search-form');
// 搜索栏搜索数据
searchForm.addEventListener('submit', (event) => {
    event.preventDefault();
    // 获取表单参数
    let formData = new FormData(searchForm);
    // 创建 URLSearchParams 对象
    let searchParams = new URLSearchParams(formData);
    // 获取查询字符串
    let params = searchParams.toString();
    // 将表单参数添加到url中
    gridOptions.server.url = addQueryParam(url, params)
    // 刷新表格
    gridInstance.updateConfig(gridOptions).forceRender();
});



    // ============ 登录状态校验 ============
if (localStorage.getItem('user') !== 'true') {
    alert('请先登录系统！');
    window.location.href = 'login.html';
    // 阻止后续代码执行
    throw new Error('未登录，已跳转');
  }
  
function logout() {
    if (confirm('确定要退出登录吗？')) {
        fetch('/api/rest/user/logout', {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            // 无论后端响应如何，都清除本地登录状态并跳转
            localStorage.removeItem('user');
            window.location.href = 'login.html';
        })
        .catch(error => {
            console.error('登出请求失败:', error);
            // 即使请求失败也清除本地状态并跳转
            localStorage.removeItem('user');
            window.location.href = 'login.html';
        });
    }
}

  // 在url末尾添加请求参数
  function addQueryParam(url, param) {
      // 如果URL中已经有查询参数，则使用&来添加新参数
      // 如果没有，则使用?来添加第一个参数
      let separator = url.indexOf('?') !== -1 ? '&' : '?';
      // 添加参数到URL
      return url + separator + param;
  }
  



  function initGrid() {
  if (gridInstance) {
    gridInstance.destroy(); // 销毁旧实例（用于刷新时重建）
  }
  gridInstance = new gridjs.Grid(gridOptions).render(document.getElementById("gridjs-container"));
}
  // 使用gridjs初始化表格
  /*function initGrid() {
    if (gridInstance) {
      gridInstance.destroy(); // 销毁旧实例（用于刷新时重建）
    }
  
    gridInstance = new gridjs.Grid({
      columns: columns,
      server: {
          url: url,
          then: data => {
              userData = data.content
              return data.content.map(
                  user => [
                      user.id, 
                      user.username, 
                      user.name, 
                      user.email, 
                      user.phone, 
                      user.createAt, 
                      user.enableState, 
                      user.dept.name
                  ]
              )
          },
          total: data => data.totalElements
      },
      pagination: {
        limit: 5, // 每页5条
        server: {
          url: (prev, page, limit) => addQueryParam(prev, `size=${limit}&page=${page}`)
        }
      },
      search: true, // 启用搜索
      sort: true,   // 启用排序
      language: {
        search: {
          placeholder: '搜索用户...'
        },
        pagination: {
          previous: '上一页',
          next: '下一页',
          showing: '显示第',
          of: '条，共',
          to: '至',
          results: '条记录'
        }
      }
    }).render(document.getElementById("gridjs-container"));
  }
  */



  document.addEventListener('DOMContentLoaded', function() {
    initGrid();
    initDept();
    initRole();
        // 填充edit表单
    gridInstance.on('cellClick', (...args) => {
        const event = args[0]
        const userId = args[3].cells[0].data
        let user = userData.find(i => i.id === userId);
        if (event.target) {
            editForm.elements['id'].value = userId
            // 执行按钮点击后的逻辑
            editForm.querySelector('[name="username"]').value = user.username;
            // 给用户名输入框赋值
            editForm.querySelector('[name="name"]').value = user.name;
            // 给手机号码输入框赋值
            editForm.querySelector('[name="phone"]').value = user.phone;
            // 给邮箱输入框赋值
            editForm.querySelector('[name="email"]').value = user.email;
            // 给部门选择框赋值
            editForm.querySelector('[name="deptId"]').value = user.dept.id;
            // 给角色选择框赋值
            editForm.querySelector('[name="roleId"]').value = user.role.id;
        }
    });
  });


  // 获取部门列表
function initDept() {
    fetch('/api/rest/dept/all')
            .then((response) => response.json())
            .then((data) => {
              let addSelectElement = addForm.querySelector('[name="deptId"]');
              let editSelectElement = editForm.querySelector('[name="deptId"]'); 
              data.forEach(item => {
                let option = document.createElement('option');
                option.value = item.id;
                option.innerText = item.name;
                // 为两个select都创建独立的option元素
                let addOption = option.cloneNode(true);
                let editOption = option.cloneNode(true);

                addSelectElement.appendChild(addOption);
                editSelectElement.appendChild(editOption);
              });
            })
            .catch(error => {
              // 处理错误
              console.error('Error:', error);
            });
}

function initRole() {
    fetch('/api/rest/role/all')
        .then((response) => response.json())
        .then((data) => {
            let addSelectElement = addForm.querySelector('[name="roleId"]');
            let editSelectElement = editForm.querySelector('[name="roleId"]');
            data.forEach(item => {
            let option = document.createElement('option');
                option.value = item.id;
                option.innerText = item.name;
                // 为两个select都创建独立的option元素
                let addOption = option.cloneNode(true);
                let editOption = option.cloneNode(true);

                addSelectElement.appendChild(addOption);
                editSelectElement.appendChild(editOption);
            });
        })
        .catch(error => {
            // 处理错误
            console.error('Error:', error);
        });
}

// 表单数据转换成json格式
function formJsonData(form) {
    const jsonData = {}
    const formData = new FormData(form);
    formData.forEach((value, key) => {
    if (!jsonData[key]) {
        jsonData[key] = formData.getAll(key).length > 1 ? formData.getAll(key) : formData.get(key);
    }
    });
    return jsonData;
}


// 文件上传
let fileInput = document.getElementById('e_fileInput');
fileInput.addEventListener('change', function () {
    // 在这里处理选择的文件
    const file = fileInput.files[0];
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', '头像');
    fetch('/api/rest/attachment', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => editForm.querySelector('[name="avatar"]').value = data.id);
});


let editForm = document.getElementById('edit-form');
// 编辑表单提交
editForm.addEventListener('submit', (event) => {
    event.preventDefault();
    if (editForm.checkValidity()) {
        // 获取表单参数
        let jsonData = formJsonData(editForm)
        fetch(`${url}/${jsonData.id}`, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(jsonData)
        }).then(response => {
            if (response.ok) {
                // 获取模态框 DOM 元素，关闭模态框
                const userModal = document.getElementById('editModal');
                bootstrap.Modal.getInstance(userModal).hide();

                initGrid(); // 重新渲染表格

                Toastify({
                    text: "编辑用户成功",
                    duration: 3000,
                    close: true,
                    backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
                    style: {
                        borderRadius: "10px"
                    }
                }).showToast();
            } else {
                response.json().then(data => {
                    // 弹出预警框
                    alert(data.message, 'danger', document.getElementById('alertEditMessage'))
                })
            }
        });
    } else {
        // 如果表单无效，添加was-validated类来显示Bootstrap验证样式
        editForm.classList.add('was-validated');
    }
})

// 监听新增按钮
addForm.addEventListener('submit', (event) => {
    event.preventDefault();
if (addForm.checkValidity()) {
    // 获取表单参数
    let jsonData = formJsonData(addForm)
    fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(jsonData)
    }).then(response => {
    if (response.ok) {
        // 获取模态框 DOM 元素，关闭模态框
        const userModal = document.getElementById('addModal');
        bootstrap.Modal.getInstance(userModal).hide();

        initGrid(); // 重新渲染表格

        Toastify({
            text: "成功添加新用户",
            duration: 3000,
            close: true,
            backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
            style: {
            borderRadius: "10px"
            }
        }).showToast();
    } else {
        response.json().then(data => {
            // 弹出预警框
            alert(data.message, 'danger', document.getElementById('alertAddMessage'))
        })
        }
    });
} else {
    // 如果表单无效，添加was-validated类来显示Bootstrap验证样式
    addForm.classList.add('was-validated');
}
});

function toggle(id) {
    fetch(url + '/' + id + '/toggle', {method: 'PATCH'})
    .then(response => gridInstance.forceRender())
    .catch(error => {
        console.error('Error:', error);
    });
}
